var express = require('express');
var router = express.Router();
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const request = require('request');
const qs = require('querystring');
/* GET home page. */
router.get('/', function (req, res, next) {
  // 测试上一个禁止IP中间件返回的自定义属性
  // console.log(res.stop);

  // 修改文件权限为 755 (rwxr-xr-x)  文件权限不支持直接修改
  const filePath = "/images/18674167d277a3da299c9b000.png";
  const command = `chmod 755 ${filePath}`;
  // exec(command, (error, stdout, stderr) => {
  // if (error) {
  //   console.error(`执行错误: ${error}`);
  //   return;
  // }
  // if (stderr) {
  //   console.error(`stderr: ${stderr}`);
  //   return;
  // }
  // console.log(`文件权限已成功修改`);
  // });
  fs.chmod(path.join(__dirname,"../public/images"),0o000,(err) => {
    if (err) {
      console.log(err);
    } else {
      console.log('File permissions changed successfully.');
    }
  });
  res.render('index', { title: 'Express' });
});
// 查询天气信息
router.get('/weather', function (req, res, next) {
  const ipArr = ["192.168.1.1", "192.168.84.36"]
  // 根据IP查城市信息
  function ipWeather(ip, callback) {
    request({
      url: "https://webapi-pc.meitu.com/common/ip_location?ip" + ip,
      json: true,
    }, (err, resp, body) => {
      if (err) {
        res.send("IP查询城市错误")
      }
      let city = body['data']['39.170.63.228']['city']
      geo2weather(city)
    })
  }
  // 根据城市查询天气
  function geo2weather(address) {
    const params = {
      key: "bd1d5faf040feace926cef9facf469a1",
      city: address
    }
    // url地址中含有特殊字符时(如中文)会报错 “Request path contains unescaped characters” 可用querystring模块来转换
    var url = 'https://restapi.amap.com/v3/weather/weatherInfo?' + qs.stringify(params)
    request({
      url,
      json: true,
    }, (err, resp, body) => {
      res.json(body);
    })
  }
  ipWeather("121.43.187.236")
});

module.exports = router;
